import * as request from '../constant/fetchRequest'
import HTTP_CODE from '../constant/httpCode'
import { message } from 'antd'

export const login = (user, programCodeSearch) => {
  return () => {
    (async () => {
      const res = await request.post(`/learn/api/auth/username${programCodeSearch}`, user)
      if (res.status === HTTP_CODE.OK) {
        message.success('Login success')
        window.localStorage.setItem('jwt', res.body.jwt)
        window.localStorage.setItem('sessionId', res.body.sessionId)
        window.location.href = '/learn/program-center/student/index.html#/'
      }
    })()
  }
}

export const wechatLogin = (code, callback) => {
  return (dispatch) => {
    (async () => {
      const res = await request.get(`/learn/api/auth/wechat?code=${code}`)
      if (res.status === HTTP_CODE.OK) {
        if (isBinding(res.body)) {
          window.localStorage.setItem('jwt', res.body.jwt)
          window.localStorage.setItem('sessionId', res.body.sessionId)
          window.location.href = '/learn/home/index.html'
        } else {
          dispatch({ type: 'GET_SOCIAL_INFO', data: {id: res.body.id} })
          callback()
        }
      }
    })()
  }
}

export const createUser = user => {
  return dispatch => {
    (async () => {
      const res = await request.post(`/learn/api/auth/users/register`, user)
      if (res.status === HTTP_CODE.CREATED) {
        window.localStorage.setItem('jwt', res.body.jwt)
        window.localStorage.setItem('sessionId', res.body.sessionId)
        dispatch({ type: 'GET_SOCIAL_INFO', data: {} })
        window.location.href = `/learn/home/index.html#/app-center`
      }
    })()
  }
}
export const getSocialAccount = (id) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`/learn/api/auth/socialAccount/${id}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({type: 'GET_SOCIAL_INFO', data: res.body})
      }
    })()
  }
}
export const submitEmail = (email) => {
  return dispatch => {
    (async () => {
      const res = await request.post(`/learn/api/auth/passwordReset`, email)
      if (res.status === HTTP_CODE.CREATED) {
        message.success(res.body.message)
      }
    })()
  }
}

export const submitPassword = (passwordInfo) => {
  return dispatch => {
    (async () => {
      const res = await request.update(`/learn/api/auth/passwordReset`, passwordInfo)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success(res.body.message)
      }
    })()
  }
}

export const userJoinProgram = programCode => {
  console.log(programCode)
  return dispatch => {
    (async () => {
      const res = await request.post(`/learn/api/auth/users/joinProgram`, programCode)
      message.success('success')
      window.location.href = `/learn/program-center/student/index.html#/`
    })()
  }
}

const isBinding = (data) => {
  return data.jwt !== undefined
}
